package TestDemo.example.fitter;

import TestDemo.example.utils.CurrentHolder;
import TestDemo.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;


import java.io.IOException;

@Slf4j
@WebFilter (value = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始进入过滤器");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("请求的url是{}",request.getRequestURI());
        if (request.getRequestURI().contains("/login")) {
            log.info("登录请求放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token=request.getHeader("token");
        log.info("请求的token是{}",token);
        if (token==null||token.isEmpty()) {
            log.info("请求头没有token{}",token);
            response.setStatus(401);
            return;
        }

        try {
            Claims jwtTokeen= JwtUtils.parseToken(token);
            log.info("jwtTokeen是{}",jwtTokeen);
            CurrentHolder.setCurrentId(Integer.valueOf(jwtTokeen.get("id").toString()));
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(401);
            return;
        }

        log.info("放行");
        filterChain.doFilter(servletRequest,servletResponse);
        //程序执行成功后还会回来的

        CurrentHolder.remove();
    }

}
